package com.daaug.demo.robotlegs.texttospeech.services
{
	import com.daaug.demo.robotlegs.texttospeech.models.TxtAudioModel;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import org.osmf.events.LoaderEvent;
	import org.robotlegs.mvcs.Actor;
	
	public class GoogleTranslateService extends Actor
	{
		[Inject]
		public var model:TxtAudioModel;
		
		private const googleTTSURL:String = "http://translate.google.com/translate_tts";
		
		private var resultSound:Sound;
		
		public function getAudio(val:String):void {
			// retrieve audio from Google Translate
			trace("translating: " + val);
			
			var variables:URLVariables = new URLVariables();
			variables.q = val;
			
			var req:URLRequest = new URLRequest(googleTTSURL);
			req.method = URLRequestMethod.GET;
			req.data = variables;
			
			resultSound = new Sound();
			resultSound.addEventListener(Event.COMPLETE, getAudioComplete);
			resultSound.addEventListener(IOErrorEvent.IO_ERROR, getAudioError);
			resultSound.load(req);
		}
		
		private function getAudioComplete(event:Event):void {
			// store result in TxtAudioModel
			model.audio = resultSound;
		}
		
		private function getAudioError(event:IOErrorEvent):void {
			trace("Oops!");
			trace(event.text);
		}
	}
}